var $dataInfo = $('#courseArrangeTable');
var phoneList = [];//手机号列表
var participantsList = [];//参课人列表
var getRegistList = [];//回显报名人id
var getCustomerId;
var getCourseArrangeId;

//防止表头与表格不对齐
$(window).resize(function () {
    $dataInfo.bootstrapTable('resetView');
});


$(function () {
    dataInfoInit();

    // 初始化下拉菜单(赠品除外)
    $('form select:not("#giftList")').selectpicker({
        // liveSearch: false,
        sanitize: true,
        size: 10,
    });
    getSelectProducts()
    // $('#customerId').selectpicker();


    $(document).on("click", "#delBtn", function () {
        var index = $(this).parents('.list').index()
        phoneList.splice(index,1);//手机号列表
        participantsList.splice(index,1);//参课人列表
        $(this).parents('.list').remove()
    })

});


/**
 * 客户名称
 */
function initCustomerSelect(productCode) {
    $.ajax({
        type: 'GET',
        dataType: "json",
        url: '/customerController/selectCustomersByProductCode?productCode=' + productCode,
        cache: false,
        async: false,
        success: (function (data) {
            if (data.code == "000000") {
                var html = '<option value="">请选择</option>';
                $.each(data.data, function (n, value) {
                    html += "<option value=" + value.customerId + ">" + value.customerName + "</option>";
                });
                $("#customerId").html(html);
            } else {
                $.alert("请求失败");
            }
        }),
        error: (function (res) {
            $.alert("请求失败");
        })
    });
}


function getSelectProducts(){
    var customerId = $('#customerId').val();
    var productCode = $('#productCode').val();

    $.ajax({
        type: 'GET',
        dataType: "json",
        url: '/customerController/selectProductsByCustomerId?customerId=' + customerId +"&productCode="+ productCode,
        cache: false,
        // async: false,
        success: (function (data) {
            if (data.code == "000000") {

                var data = data.data;

                var productListHtml = '';
                for (var i = 0; i < data.length; i++) {
                    productListHtml += "<option value=" + data[i].finishOrderProductNum + " >" + data[i].productName + "-剩余" + data[i].serviceNumber + "次" + " (" + data[i].productCategories + ")" + "</option>"
                }

                $('#productList').html('<option value="1">全部产品</option>' + productListHtml).selectpicker('refresh');
                $('#giftList').html(productListHtml).multiselect("destroy").multiselect({
                    filterPlaceholder: '搜索',
                    enableFiltering: true,
                    includeSelectAllOption: false,
                    maxHeight: 300,
                    selectAllText: '全部选择',
                    nonSelectedText: '请选择',
                    nSelectedText: '已选择',
                    allSelectedText: '已选择全部',
                    buttonWidth: '100%',
                    buttonText: function(options, select) {
                        if (options.length === 0) {
                            return '请选择产品';
                        } else {
                            return '已选择' + options.length + '个会员卡';
                        }
                    },
                    onChange: function () {

                    },
                    onSelectAll: function () {
                        return '已选择全部'
                    },
                    onDeselectAll: function () {

                    }
                });


                // var html = '<option value="">请选择</option>';
                // $.each(data.data, function (n, value) {
                //     html += "<option value=" + value.finishOrderProductNum + ">" + value.productName + "-剩余" + value.serviceNumber + "次" + " (" + value.productCategories + ")" + "</option>";
                // });
                // $("#productNums").html(html);
            } else {
                $.alert("请求失败");
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });

}




/**
 * 选择客户时，获取客户下产品
 */
function changeProducts() {
    getSelectProducts()
    getRegistList = [];
    var customerId = $('#customerId').val();
    var html1 = '';
    html1 += ' <div class="list" >\n' +
        '                                <div class="form-group col-lg-5 col-md-5 col-sm-5 col-xs-12" style="display: flex">\n' +
        '                                    <span>参课人：</span>\n' +
        '                                    <input type="text"  class="form-control usercourse" style="width: 60%" >\n' +
        '                                </div>\n' +
        '                                <div class="form-group col-lg-5 col-md-5 col-sm-5 col-xs-11" style="display: flex">\n' +
        '                                    <span>联系方式：</span>\n' +
        '                                    <input type="text"  class="form-control phone" style="width: 60%" maxlength="11">\n' +
        '                                </div>\n' +
        '                                <div class="form-group col-lg-2 col-md-2 col-sm-2 col-xs-2" style="display: flex">\n' +
        '                                    <button type="button" class="btn btn-primary pull-right" id="delBtn" style="width: auto;height: 30px;line-height: 25px;padding:0 10px;">删除参课人</button>\n' +
        '                                </div>\n' +
        '                            </div>'
    $('#courseContactList').html(html1)
    $.ajax({
        type: 'get',
        dataType: "json",
        url: ' /courseArrange/getRegistByCourseIdAndCustomerId',
        cache : false,
        // contentType: "application/json;charset=utf-8",
        data:{
            customerId: customerId,
            courseId:getCourseArrangeId
        },
        async : false,
        success: (function (data) {
            if (data.code == "000000") {
                var html = '';
                $.each(data.data,function(index,item){
                    phoneList[index] = item.contactWay;//手机号列表
                    participantsList[index] = item.applyName;//参课人列表
                    getRegistList.push(item.courseRegistrationId);//回显报名人id
                    html += ` <div class="list" >
                                <div class="form-group col-lg-5 col-md-5 col-sm-5 col-xs-12" style="display: flex">
                                    <span>参课人：</span>
                                    <input type="text"  class="form-control usercourse" style="width: 60%"  value="${item.applyName}">
                                </div>
                                <div class="form-group col-lg-5 col-md-5 col-sm-5 col-xs-11" style="display: flex">
                                    <span>联系方式：</span>
                                    <input type="text"  class="form-control phone" style="width: 60%" maxlength="11" value="${item.contactWay}">
                                </div>
                                <div class="form-group col-lg-2 col-md-2 col-sm-2 col-xs-2" style="display: flex">
                                    <button type="button" class="btn btn-primary pull-right" id="delBtn" style="width: auto;height: 30px;line-height: 25px;padding:0 10px;">删除参课人</button>
                                </div>
                            </div>`
                })
                $('#courseContactList').prepend(html);

            } else {
                alert("请求失败");
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });

}


/**
 * 课程管理
 */
function dataInfoInit() {
    //先销毁表格
    $dataInfo.bootstrapTable('destroy');
    $dataInfo.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/courseArrange/getCourseManagerList',//请求地址
        method: 'get',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'courseArrangeId',
        idField: 'courseArrangeId',
        pageSize: globalPageSize,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: globalPageList,//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedNumber: 4,         // 左侧固定列
        // fixedRightNumber: 1,    // 右侧固定列
        queryParams: queryParams,//查询参数
        columns: [
            {title: '客户id', field: 'courseArrangeId', visible: false},
            {title: '课程id', field: 'courseId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'middle', formatter: indexFormat},
            {title: '课程名称', field: 'courseName', align: 'left', valign: 'middle'},
            {title: '课程类别', field: 'courseCategory', align: 'left', valign: 'middle'},
            {title: '课程小类', field: 'courseSubCategory', align: 'left', valign: 'middle'},
            {title: '产品编码', field: 'productCode', align: 'left', valign: 'middle'},
            {title: '服务次数', field: 'serviceTimes', width: '30', align: 'left', valign: 'middle'},
            {title: '报名开始时间', field: 'enterStartTm', align: 'left', valign: 'middle', formatter: dateFormat},
            {title: '报名结束时间', field: 'enterEndTm', align: 'left', valign: 'middle', formatter: dateFormat},
            {title: '开课日期', field: 'courseStartTm', align: 'left', valign: 'middle', formatter: dateFormat},
            {title: '开课地点', field: 'courseStartPlace', align: 'left', valign: 'middle'},
            {title: '操作', field: 'operate', align: 'right', formatter: genderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}


/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    var html = '<button type="button" class="btn btn-default" data-toggle="modal" onclick="enterCourse(\'' + row.courseName + '\',\'' + row.serviceTimes + '\',\'' + row.courseStartTm + '\',\'' + row.enterStartTm + '\',\'' + row.enterEndTm + '\',\'' + row.productCode + '\',\'' + row.courseStartPlace + '\',\'' + row.courseArrangeId + '\',\'' + row.courseId + '\')"><i class="mdi mdi-eye"></i>报名参加</button>';
    html += '<button type="button" class="btn btn-default" onclick="generateCode(\'' + row.courseArrangeId + '\')"><i class="mdi mdi-pencil"></i>生成二维码</button>';
    return html;
}


/**
 * 拼接查询条件参数
 */
function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    params.bs = '1';  //0管理端 1用户端
    return params;
}

function addCourseContact() {
    var html = '';
    html += ' <div class="list" >\n' +
        '                                <div class="form-group col-lg-5 col-md-5 col-sm-5 col-xs-12" style="display: flex">\n' +
        '                                    <span>参课人：</span>\n' +
        '                                    <input type="text"  class="form-control usercourse" style="width: 60%" >\n' +
        '                                </div>\n' +
        '                                <div class="form-group col-lg-5 col-md-5 col-sm-5 col-xs-11" style="display: flex">\n' +
        '                                    <span>联系方式：</span>\n' +
        '                                    <input type="text"  class="form-control phone" style="width: 60%" maxlength="11">\n' +
        '                                </div>\n' +
        '                                <div class="form-group col-lg-2 col-md-2 col-sm-2 col-xs-2" style="display: flex">\n' +
        '                                    <button type="button" id="delBtn" class="btn btn-primary pull-right" style="width: auto;height: 30px;line-height: 25px;padding:0 10px;">删除参课人</button>\n' +
        '                                </div>\n' +
        '                            </div>'
    $('#courseContactList').prepend(html)
}

/**
 * 时间转换
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function dateFormat(value, row, index) {
    if (value != null) {
        var date = new Date(value);
        var month = date.getMonth() + 1;
        var tian = date.getDate();
        var hour = date.getHours();
        var minute = date.getMinutes();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (tian >= 1 && tian <= 9) {
            tian = "0" + tian;
        }
        if (hour >= 1 && hour <= 9) {
            hour = "0" + hour;
        }
        if (minute >= 1 && minute <= 9) {
            minute = "0" + minute;
        }

        return date.getFullYear() + '-' + month + '-' + tian+ ' ' +hour+':'+minute;
    }
}

//报名参加
function enterCourse(courseName, serviceTimes, courseStartTm, enterStartTm, enterEndTm, productCode, courseStartPlace, courseArrangeId,courseId) {
     phoneList = [];//手机号列表
     participantsList = [];//参课人列表
    initCustomerSelect(productCode);

    var nowtimeYMDHM = new Date().FormatFMT("yyyy-MM-dd hh:mm");
    if (enterEndTm < nowtimeYMDHM) {
        $.alert(courseName + "-报名已结束！")
        return;
    }
    if (nowtimeYMDHM < enterStartTm) {
        $.alert(courseName + "-报名未开始！")
        return;
    }
    resetBtn()
    getCourseArrangeId = courseArrangeId;
    $('#courseName').text(courseName);
    // $('#courseTime').text(dateFormat(Number(enterStartTm)) + ' 至 ' + dateFormat(Number(enterEndTm)));
    $('#courseTime').text(enterStartTm + ' 至 ' + enterEndTm);
    $('#courseAddress').text(courseStartPlace);
    $('#staticBackdrop').modal('show');
    $('#productCode').val(productCode);
    $('#courseServiceTimes').val(serviceTimes);

}


//重置按钮
function resetBtn() {
    $('#customerId').val('');
    $('#customerId').selectpicker('refresh');
    var html = '';
    html += ' <div class="list" >\n' +
        '                                <div class="form-group col-lg-5 col-md-6 col-sm-6 col-xs-12" style="display: flex">\n' +
        '                                    <span>参课人：</span>\n' +
        '                                    <input type="text"  class="form-control usercourse" style="width: 60%" >\n' +
        '                                </div>\n' +
        '                                <div class="form-group col-lg-5 col-md-5 col-sm-5 col-xs-11" style="display: flex">\n' +
        '                                    <span>联系方式：</span>\n' +
        '                                    <input type="text"  class="form-control phone" style="width: 60%" maxlength="11">\n' +
        '                                </div>\n' +
        '                                <div class="form-group col-lg-2 col-md-2 col-sm-2 col-xs-2" style="display: flex">\n' +
        '                                    <button type="button" id="delBtn" class="btn btn-primary pull-right" style="width: auto;height: 30px;line-height: 25px;padding:0 10px;">删除参课人</button>\n' +
        '                                </div>\n' +
        '                            </div>'
    $('#courseContactList').html(html)
    $('#exampleFormControlTextarea1').val('')
}

//提交
function submit() {
    let list = $('.multiselect ').attr('title').split(',')
    let serviceTimesList = [];
    let productCategoriesList = [];
    let productList = []
    if($('#giftList').val()){
        for(var i = 0;i<$('#giftList').val().length;i++){
            serviceTimesList.push(Number(list[i].replace(/[^0-9]/ig,"")))
            if(list[i].substring(list[i].indexOf("(")+1,list[i].indexOf(")")) == '会员'){
                productCategoriesList.push(1)
            }else{
                productCategoriesList.push(0)
            }
        }
        for(var j = 0 ; j<$('#giftList').val().length;j++){
            let obj = {}
            obj.productNum = $('#giftList').val()[j];
            obj.serviceTimes = serviceTimesList[j];
            obj.productCategories = productCategoriesList[j];
            productList.push(obj)
        }
    }


    // $.ajax({
    //     type: 'POST',
    //     dataType: "json",
    //     url: '/courseArrange/addCourseRegist',
    //     contentType: "application/json;charset=utf-8",
    //     data:JSON.stringify({
    //         customerId:$('#customerId').val(),
    //         courseArrangeId:getCourseArrangeId,
    //         applyNames:participantsList,
    //         contactWays:phoneList,
    //         remark:$('#exampleFormControlTextarea1').val(),
    //     }),
    //     async : false,
    //     success: (function (data) {
    //         if (data.code == "000000") {
    //             alert("添加成功!");
    //             $dataInfo.bootstrapTable('refresh');
    //         } else {
    //             alert(data.data);
    //         }
    //     }),
    //     error: (function (res) {
    //         alert("请求失败");
    //     })
    // });
    // console.log(participantsList.length)
    for (var i = 0; i < $('.list').length; i++) {
        // debugger;
        if (participantsList[i] == '' || participantsList.length == 0 && phoneList[i] == '' || phoneList.length == 0) {
            $.alert('参课人或手机号不能为空')
            return;
        }

    }
    if($('#customerId').val() == ''){
        $.alert('请选择客户名称')
        return;
    }
    $.ajax({
        type: 'POST',
        dataType: "json",
        url: '/courseArrange/addCourseRegist',
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify({
            customerId: $('#customerId').val(),
            courseServiceTimes: $('#courseServiceTimes').val(),
            productCode: $('#productCode').val(),
            courseArrangeId: getCourseArrangeId,
            applyNames: participantsList,
            contactWays: phoneList,
            remark: $('#exampleFormControlTextarea1').val(),
            product:productList,
            registList:getRegistList
        }),
        async: false,
        success: (function (data) {
            if (data.code == "000000") {
                $('#staticBackdrop').modal('hide');
                $.alert("添加成功!");
                $dataInfo.bootstrapTable('refresh');
            } else {
                $.alert(data.data);
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}

// //手机号输入查重
$(function () {
    $(document).on("blur", ".phone", function () {
        let index = $(this).parent().parent().index()
        if (phoneList.length > 0) {
            if (isMobile($(this).val())) {
                if (phoneList.indexOf($(this).val()) != -1) {
                    $.alert('电话号码不能重复')
                    $(this).val('')
                }
                phoneList[index] = $(this).val()
            } else {
                $.alert('请输入正确是手机号码')
                $(this).val('')

            }

        } else {
            if (isMobile($(this).val())) {
                phoneList[index] = $(this).val()
            } else {
                $.alert('请输入正确是手机号码')
                $(this).val('')
            }

        }
    });
    $(document).on("blur", ".usercourse", function () {
        let i = $(this).parent().parent().index()
        participantsList[i] = $(this).val()
    })
})

function isMobile(inputString) {
    var partten = /^1[34578]\d{9}$/;
    var fl = false;
    if (partten.test(inputString)) {
        return true;
    } else {
        return false;
    }
}